package com.CMUBiS.Depreciated;

import java.sql.*;
import java.util.Random;
import java.util.Date;
import java.security.*;


/**
 * Database.java - the database interface class.
 * @author John Payne
 * @version 0.1
 * The Database class is used to interface with the database.
 */
public class CassandraDb extends Database {

/** Authenticates user
 * @param userName	User's username
 * @param password	User's password 
 * 
 * @return			authToken if successful or null if failure
 * @throws  
 */
public String login(String userName, String password){
	Boolean userAuthenticated = false;
	int id=0;
	if(checkConnection()){
		try {
		    Statement stmt = getDbConnection().createStatement();
		    ResultSet rs = stmt.executeQuery("SELECT id FROM users WHERE username='"+userName+"' AND password='"+password+"'");
		    if(rs.next()){
		    	id=rs.getInt(1);
		    	if(getVerbose()){
					System.out.print("User " + userName + " successfully authenticated.\n");
					}
		    	userAuthenticated=true;
				}else{
					if(getVerbose()){
						System.out.print("User " + userName + " failed to log in.\n");
						}
				}
		    	
		} catch (Exception e) {
			if(getVerbose()){
				System.out.print(e.getMessage()+"\n");
				}
			}
				
			if (userAuthenticated){
				String authToken = authToken(id);
				try {
				    Statement stmt = getDbConnection().createStatement();
				    int result = stmt.executeUpdate("UPDATE users SET authtoken='"+authToken+"' WHERE username='"+userName+"'");
				    if (result==1){
				    	if(getVerbose()){
							System.out.print("Authentication token for " + userName + " successfully stored.\n");
							}
				    }else{
				    	if(getVerbose()){
							System.out.print("Authentication token for " + userName + " successfully stored.\n");
							}
				    }
				    				    	
				} catch (Exception e) {
					if(getVerbose()){
						System.out.print(e.getMessage()+"\n");
						}
					}
			return authToken;
		}
	}
	return null;
}

public Boolean checkAuthToken(String userName, String authToken){
	Boolean userAuthenticated = false;
	int id=0;
	if(checkConnection()){
		try {
		    Statement stmt = getDbConnection().createStatement();
		    ResultSet rs = stmt.executeQuery("SELECT id FROM users WHERE username='"+userName+"' AND authToken='"+authToken+"'");
		    if(rs.next()){
		    	id=rs.getInt(1);
		    	if(getVerbose()){
					System.out.print("User " + userName + " successfully authenticated.\n");
					}
		    	userAuthenticated=true;
				}else{
					if(getVerbose()){
						System.out.print("User " + userName + " failed to log in.\n");
						}
				}
		    	
		} catch (Exception e) {
			if(getVerbose()){
				System.out.print(e.getMessage()+"\n");
				}
			}
		
		if (userAuthenticated){
			return true;
		}
	}
	return false;
}
}
